﻿using UnityEngine;

namespace Common
{
	//继承MonoBehaviour 单例需要挂接物体对象的组件可用
	public class SingletonMono<T> : MonoBehaviour where T : Component
	{
		private static T instance; 
		
		public static T GetInstance
		{
			get
			{
				if (instance == null)
				{
					instance = FindObjectOfType<T>();
					if (instance == null)
					{
						GameObject obj = new GameObject();
						obj.name = typeof(T).Name;
						obj.hideFlags = HideFlags.DontSave;
						instance = obj.AddComponent<T>();
					}
				}
				return instance;
			}
		}
		
		public virtual void Awake()
		{
			//DontDestroyOnLoad(this.gameObject);
			if (instance == null)
			{
				instance = this as T;
			}
			else {
				Destroy(gameObject);
			}
		}
	}
}

